package cn.lanqiao.business.service.impl;

import java.io.File;
import java.sql.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.lanqiao.business.domain.Points;
import cn.lanqiao.business.domain.Semester;
import cn.lanqiao.business.domain.vo.StudnetPointsVo;
import cn.lanqiao.business.mapper.PointsMapper;
import cn.lanqiao.business.mapper.SemesterMapper;
import cn.lanqiao.common.exception.ServiceException;
import cn.lanqiao.common.utils.DateUtils;
import cn.lanqiao.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.lanqiao.business.mapper.StudentMapper;
import cn.lanqiao.business.domain.Student;
import cn.lanqiao.business.service.IStudentService;

/**
 * 学生信息Service业务层处理 
 * 
 * @author yangjianqing
 * @date 2024-07-08
 */
@Service
public class StudentServiceImpl implements IStudentService
{
    private static final Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private SemesterMapper semesterMapper;

    @Autowired
    private PointsMapper pointsMapper;

    /**
     * 查询学生信息
     * 
     * @param id 学生信息主键
     * @return 学生信息
     */
    @Override
    public Student selectStudentById(Long id)
    {
        return studentMapper.selectStudentById(id);
    }

    /**
     * 查询学生信息列表
     * 
     * @param student 学生信息
     * @return 学生信息
     */
    @Override
    public List<Student> selectStudentList(Student student)
    {
        return studentMapper.selectStudentList(student);
    }

    /**
     * 查询学生信息列表并导出到excel
     *
     * @param student 学生信息
     * @return 学生信息集合
     */
    @Override
    public List<Student> selectStudentListToExport(Student student) {
        List<Student> students = studentMapper.selectStudentListToExport(student);
        return students;
    }

    /**
     * 新增学生信息
     * 
     * @param student 学生信息
     * @return 结果
     */
    @Override
    public int insertStudent(Student student)
    {
        student.setCreateTime(DateUtils.getNowDate());
        return studentMapper.insertStudent(student);
    }

    /**
     * 修改学生信息
     * 
     * @param student 学生信息
     * @return 结果
     */
    @Override
    public int updateStudent(Student student)
    {
        student.setUpdateTime(DateUtils.getNowDate());
        return studentMapper.updateStudent(student);
    }

    /**
     * 批量删除学生信息
     * 
     * @param ids 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentByIds(Long[] ids)
    {
        return studentMapper.deleteStudentByIds(ids);
    }

    /**
     * 删除学生信息信息
     * 
     * @param id 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentById(Long id)
    {
        return studentMapper.deleteStudentById(id);
    }

    /**
     * 导入学生信息
     * @param stus 学生信息列表
     * @param stuClassId 班级编号
     * @param operName 导入人
     */
    @Override
    public String importStudent(List<Student> stus, Long stuClassId,String operName) {
        if (StringUtils.isNull(stus) || stus.size() == 0)
        {
            throw new ServiceException("导入学生数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Student stu : stus)
        {
            try
            {
                // 验证是否存在这个学生
                Student u = studentMapper.selectStudentByStuId(stu.getStuId());
                if (StringUtils.isNull(u))
                {
                    stu.setStuClassId(stuClassId);
                    stu.setCreateBy(operName);
                    studentMapper.insertStudent(stu);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + stu.getStuName() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生 " + stu.getStuName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学生 " + stu.getStuName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询指定学期积分信息
     *
     * @param studnetPointsVo 查询条件
     * @return 结果
     */
    @Override
    public List<StudnetPointsVo> selectStudentPointslist(StudnetPointsVo studnetPointsVo) {
        // 查询指定学生
        List<StudnetPointsVo> students = studentMapper.selectStudentPointslist(studnetPointsVo);
        // 遍历所有学生，取出所有学生id
        List<Long> ids = new LinkedList<>();
        for (StudnetPointsVo spv : students){
            ids.add(spv.getId());
            spv.setStuSemId(studnetPointsVo.getStuSemId());
        }
        System.out.println(ids);
        if(ids.size()!=0){
            // 调用积分模块查询每个学生本学期的积分
            List<Points>  scores = pointsMapper.selectPointsByStuIds(ids,studnetPointsVo.getStuSemId());
            // 遍历所有学生
            for (StudnetPointsVo spv : students){
                // 遍历所有积分记录
                for(Points p:scores){
                    // 判断是否为同意学生的积分，如果是就用spv对象中的总分加上这个积分
                    if (p.getStuId()==spv.getId()){
                        spv.setStuScore(spv.getStuScore()+p.getUpScore());
                    }
                }
            }
        }
        return students;
    }
}
